package com.hibase.quartz.config;

import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @Description: TODO 应用私有的调度器，不入集群，单独执行
 * @Author: liuyunlei
 * @Date: 2020/12/1 16:08
 * @Version: 1.0
 */
@Component
public class SingleScheduler {

    private Scheduler singleScheduler;

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${hibase.MdsJob.machineName:default}")
    public String machineName;

    @Value("${spring.datasource.dynamic.datasource.mysql.url}")
    public String dbUrl;

    @Value("${spring.datasource.dynamic.datasource.mysql.username}")
    public String dbUser;

    @Value("${spring.datasource.dynamic.datasource.mysql.password}")
    public String dbPassword;

    public Scheduler getInstance(){

        return singleScheduler;
    }

    public void init() {

        try {

            StdSchedulerFactory sf = new StdSchedulerFactory();
            PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
            propertiesFactoryBean.setLocation(new ClassPathResource("/singleQuartz.properties"));
            propertiesFactoryBean.afterPropertiesSet();
            Properties prop = propertiesFactoryBean.getObject();
            prop.put("org.quartz.scheduler.instanceName",machineName+"Scheduler");
            prop.put("org.quartz.dataSource.MyDS.URL",dbUrl);
            prop.put("org.quartz.dataSource.MyDS.user",dbUser);
            prop.put("org.quartz.dataSource.MyDS.password",dbPassword);
            sf.initialize(prop);
            singleScheduler = sf.getScheduler();
            singleScheduler.start();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }


}
